package com.hannesdorfmann.mosby3.mvi.integrationtest.lifecycle.fraction;

import com.hannesdorfmann.mosby3.mvi.integrationtest.ResourceTable;
import com.hannesdorfmann.mosby3.mvi.integrationtest.slice.RetainingFractionAbilitySlice;
import ohos.aafwk.ability.fraction.Fraction;
import ohos.aafwk.ability.fraction.FractionAbility;
import ohos.aafwk.content.Intent;

import java.util.Optional;

public class RetainingFractionAbility extends FractionAbility {

    private static volatile RetainingFractionAbility currentInstance;
    private static final String TAG = "Test-Fragment";


    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
//        super.setMainRoute(RetainingFractionAbilitySlice.class.getName());
        currentInstance = getInstance();
        super.setUIContent(ResourceTable.Layout_ability_lifecycle);


        SimpleRetainingMviLifecycleFraction f = new SimpleRetainingMviLifecycleFraction();
        currentInstance.getFractionManager()
                .startFractionScheduler()
                .replace(ResourceTable.Id_container, f)
                .pushIntoStack(TAG)
                .submit();
    }

    public static RetainingFractionAbility getInstance(){
        if(RetainingFractionAbility.currentInstance == null){
            RetainingFractionAbility.currentInstance = new RetainingFractionAbility();
        }
        return  RetainingFractionAbility.currentInstance;
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    public SimpleRetainingMviLifecycleFraction getFragment(){
        Optional<Fraction> fractionOptional = currentInstance.getFractionManager().getFractionByTag(TAG);
        return (SimpleRetainingMviLifecycleFraction) fractionOptional.get();
    }

    public static void pressBackButton() {
        currentInstance.getUITaskDispatcher().syncDispatch(new Runnable() {
            @Override public void run() {
                currentInstance.onBackPressed();
            }

        });
    }
}
